/*///////////////////////////////////////////////////////////
*
* FILE:		client.c
* AUTHOR:	Reid Harrison
* PROJECT:	CS 3251 Project 1 - Professor Traynor
* DESCRIPTION:	Network Client Code
*
*////////////////////////////////////////////////////////////

/* Included libraries */

#include <stdio.h>        /* for printf() and fprintf() */
#include <sys/types.h>
#include <sys/socket.h>	  /* for socket(), connect(), send(), and recv() */
#include <arpa/inet.h>	  /* for sockaddr_in and inet_addr() */
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <openssl/sha.h>

/* Constants */
#define RCVBUFSIZE 512	        /* The receive buffer size */
#define SNDBUFSIZE 512	        /* The send buffer size */

/* The main function */
int main(int argc, char *argv[])
{

    int clientSock;		    /* socket descriptor */
    struct sockaddr_in serv_addr;   /* The server address */

    char *studentName;		    /* Your Name */

    char sndbuf[SNDBUFSIZE];	    /* Send Buffer */
    char rcvbuf[RCVBUFSIZE];	    /* Receive Buffer */
    
    char *addr = "127.0.0.1";
    in_port_t servPort = 2000;

    /* Get the Student Name from the command line */
    if (argc != 2) 
    {
	    printf("Incorrect input format. The correct format is:\n\tnameChanger your_name\n");
	    exit(1);
    }
    studentName = argv[1];
    
    /* Create a new TCP socket*/
    clientSock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (clientSock < 0)
        exit(1);
        
    /* Construct the server address structure */
    memset(&serv_addr, 0, sizeof(serv_addr));
    serv_addr.sin_family = AF_INET;
    
    int rtnVal = inet_pton(AF_INET, addr, &serv_addr.sin_addr.s_addr);
    if (rtnVal == 0)
        exit(1);
        
    serv_addr.sin_port = htons(servPort);
    
    /* Establish connection to the server */
    if (connect(clientSock, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0)
        exit(1);
        
    size_t echoStringLen = strlen(studentName);
    
    /* Send the string to the server */
    ssize_t numBytes = send(clientSock, studentName, SNDBUFSIZE, 0);
    if (numBytes < 0)
        exit(1);
        
    unsigned int totalBytes = 0;
    fputs("Received: ", stdout);
    
    /* Receive and print response from the server */
    while (totalBytes < echoStringLen) {
        numBytes = recv(clientSock, rcvbuf, RCVBUFSIZE, 0);
        totalBytes += numBytes;
        rcvbuf[numBytes] = '\0';
        fputs(rcvbuf, stdout);
    }
    
    fputc('\n', stdout);
    
    close(clientSock);
    exit(0);

    printf("%s\n", studentName);

    return 0;
}

